package com.masterlu.module.trade.service.order2;

import com.masterlu.module.pay.api.order.PayOrderApi;
import com.masterlu.module.pay.api.order.dto.PayOrderCreateReqDTO;
import com.masterlu.module.trade.controller.app.order2.vo.PackageOrderCreateReqVO;
import com.masterlu.module.trade.controller.app.order2.vo.PackageOrderPageReqVO;
import com.masterlu.module.trade.dal.dataobject.order2.PackageOrderDO;
import com.masterlu.module.trade.dal.mysql.order2.PackageOrderMapper;
import com.masterlu.module.trade.dal.redis.no.TradeNoRedisDAO;
import com.masterlu.module.trade.enums.order.TradeOrderRefundStatusEnum;
import com.masterlu.module.trade.enums.order.TradeOrderStatusEnum;
import com.masterlu.module.trade.enums.order.TradeOrderTypeEnum;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import com.masterlu.framework.common.pojo.PageResult;
import com.masterlu.framework.common.util.object.BeanUtils;

import java.time.LocalDateTime;

import static com.masterlu.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.masterlu.framework.common.util.servlet.ServletUtils.getClientIP;
import static com.masterlu.framework.web.core.util.WebFrameworkUtils.getTerminal;
import static com.masterlu.module.trade.enums.ErrorCodeConstants.ORDER_NOT_EXISTS;
/**
 * 套餐订单 Service 实现类
 *
 * @author 陆师傅源码
 */
@Service
@Validated
public class  PackageOrderServiceImpl implements  PackageOrderService {

    @Resource
    private PackageOrderMapper packageOrderMapper;
    @Resource
    private PayOrderApi payOrderApi;
    @Resource
    private TradeNoRedisDAO tradeNoRedisDAO;

    @Override
    public PackageOrderDO createOrder(Long userId, PackageOrderCreateReqVO createReqVO) {
        // 创建packageOrder套餐订单
        PackageOrderDO order =buildPackageOrder(userId,createReqVO);
        packageOrderMapper.insert(order);
        // 4. 订单创建后的逻辑
        afterCreateTradeOrder(order,createReqVO);

        return order;
    }

    private PackageOrderDO buildPackageOrder(Long userId, PackageOrderCreateReqVO createReqVO) {
        PackageOrderDO order = new PackageOrderDO();
        order.setNo(tradeNoRedisDAO.generate(TradeNoRedisDAO.TRADE_ORDER_NO_PREFIX));//订单流水号
        order.setTerminal(getTerminal()); /*订单来源终端*/
        order.setType(TradeOrderTypeEnum.NORMAL.getType()); //订单类型
        order.setStatus(TradeOrderStatusEnum.UNPAID.getStatus()); //订单状态
        order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus()); //退款状态
        order.setUserId(userId);  /*用户Id*/
        order.setUserIp(getClientIP()).setTerminal(getTerminal());  //用户IP
        order.setPackageId(createReqVO.getPackageId()); /*订单ID*/
        order.setPayPrice(createReqVO.getPayPrice());/*订单金额*/
        order.setRemark(createReqVO.getRemark());/*订单描述*/
        order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus()).setRefundPrice(0); //退款状态
        return order;
    }
    /**
     * 订单创建后，执行后置逻辑
     * <p>
     * 例如说：优惠劵的扣减、积分的扣减、支付单的创建等等
     *
     * @param order       订单
     * @param createReqVO 创建订单请求
     */
    private void afterCreateTradeOrder(PackageOrderDO order,
                                       PackageOrderCreateReqVO createReqVO) {
        // 3. 生成预支付
        createPayOrder(order);

        // 4. 插入订单日志
       /* TradeOrderLogUtils.setOrderInfo(order.getId(), null, order.getStatus());*/

        // TODO @LeeYan9: 是可以思考下, 订单的营销优惠记录, 应该记录在哪里, 微信讨论起来!
    }

    private void createPayOrder(PackageOrderDO order) {
        // 创建支付单，用于后续的支付
        PayOrderCreateReqDTO payOrderCreateReqDTO =new PayOrderCreateReqDTO();
        payOrderCreateReqDTO.setAppId(1L);//
        payOrderCreateReqDTO.setUserIp(order.getUserIp());
        payOrderCreateReqDTO.setSubject(order.getRemark());
        payOrderCreateReqDTO.setBody(order.getRemark());
        payOrderCreateReqDTO.setPrice(order.getPayPrice());
        payOrderCreateReqDTO.setMerchantOrderId(String.valueOf(order.getId())); /*暂时不起作用*/
        payOrderCreateReqDTO.setExpireTime(LocalDateTime.now().plusHours(1)); /*暂时设置1小时超时*/

        Long payOrderId = payOrderApi.createOrder(payOrderCreateReqDTO);

        // 更新到交易单上
        packageOrderMapper.updateById(new PackageOrderDO().setId(order.getId()).setPayOrderId(payOrderId));
        order.setPayOrderId(payOrderId);
    }

    @Override
    public void updateOrder(PackageOrderCreateReqVO updateReqVO) {
        // 校验存在
        validateOrderExists(updateReqVO.getId());
        // 更新
        PackageOrderDO updateObj = BeanUtils.toBean(updateReqVO, PackageOrderDO.class);
        packageOrderMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrder(Long id) {
        // 校验存在
        validateOrderExists(id);
        // 删除
        packageOrderMapper.deleteById(id);
    }

    private void validateOrderExists(Long id) {
        if (packageOrderMapper.selectById(id) == null) {
            throw exception(ORDER_NOT_EXISTS);
        }
    }

    @Override
    public PackageOrderDO getOrder(Long id) {
        return packageOrderMapper.selectById(id);
    }

    @Override
    public PageResult<PackageOrderDO> getOrderPage(PackageOrderPageReqVO pageReqVO) {
        return packageOrderMapper.selectPage(pageReqVO);
    }

}